package com.sasis.webapp.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.achievo.struts.ActionContext;
import com.sasis.Constants;
import com.sasis.model.CurrentUser;
import com.sasis.model.User;

public class UserFilter implements Filter {
	private static final Log log = LogFactory.getLog(PermissionFilter.class);

	private String errorUrl;

	// private BaseDaoiBATIS basedaoibatis;

	public void init(FilterConfig filterConfig) throws ServletException {
		errorUrl = filterConfig.getInitParameter("errorPath");
		System.out.println("--------------------------errorUrl______");
		System.out.println(errorUrl);
		System.out.println("--------------------------errorUrl______");
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		
		
		try {
			HttpServletRequest httpRequest = (HttpServletRequest) request;
			HttpServletResponse httpResponse = (HttpServletResponse) response;
			HttpSession session = httpRequest.getSession();
			User user = (User)session.getAttribute("user");
			log.debug(">>>>>>>>>>>>user>>>>>>>>>>>>"+user);
			//if(null!=user)CurrentUser.set((User)session.getAttribute("user"));
			
			//set user into local thread (add by kellen 07-08-25)
            CurrentUser.set(user);
            //User user = (User)session.getAttribute("user");
            
            String isLogin = (String) session.getAttribute(Constants.CURUSER_KEY);
			if (session == null || !"true".equals(isLogin)) {
				httpRequest.setAttribute("notUserSession","Y");
				httpResponse.sendRedirect(errorUrl);
			} else {
				filterChain.doFilter(request, response);
			}

		} catch (Exception ex) {
			log.error(ex);
			ex.printStackTrace();
		}
	}

	public void destroy() {

	}

}
